let http = require('http');
let fs = require('fs');
let path = require('path');
let { promisify } = require('util');
let stat = promisify(fs.stat);

let server = http.createServer(async function (req, res) {
    let p = path.join(__dirname, 'test.png');
    let statObj = await stat(p);
    let total = statObj.size;
    let start = 0;
    let end = total;

    let range = req.headers['range'];
    if (range) {
        // res.setHeader('Accept-Ranges', 'bytes');
        let result = range.match(/bytes=(\d*)-(\d*)/);
        start = result[1] ? parseInt(result[1]) : start;
        end = result[2] ? parseInt(result[2]) : end;
        res.setHeader('Content-Range', `bytes ${start}-${end}/${total}`)
    }
    res.setHeader('Content-Type', 'text/plain;charset=utf8');
    console.log(start, end);
    // if (start <= end) {
    // res.write('输出开始');
    fs.createReadStream(p, { start, end }).pipe(res);
    // }
});
server.listen(8080);
